package kayao.server.network;

import java.io.IOException;
import java.net.DatagramPacket;
import kayao.common.KayaoDatagramSocket;
import kayao.common.KayaoValues;
import kayao.common.NetworkUtils;
import kayao.server.network.message.MessageHandler;

public class NetreadThread extends Thread {
	private static final int MAX_PACKET_SIZE = 150; // What is the maximum packet size of all our packages?
	private boolean mRunning=true;
	private boolean mDead=false;
	private KayaoDatagramSocket mSocket;
	private DatagramPacket mReceivePacket;
	private byte[] mReceiveData;
	
	public NetreadThread(KayaoDatagramSocket socket) {
		try{
			mSocket = socket;
		} catch(Exception e){
			System.out.println("Error in NetReadThread constructor: " + e.getMessage());
		}
		
		mReceiveData = new byte[MAX_PACKET_SIZE];
		mReceivePacket = new DatagramPacket(mReceiveData, mReceiveData.length);
	}
	
	public boolean terminate(){
		mRunning = false;
		mSocket.close();
		if (mSocket.isClosed() == false){
			System.out.println("(NetreadThread.terminate) Unable to close socket");
		}
		while(!mDead){
			Thread.yield();
		}
		return false;
	}
	
	@Override
	public void run() {
		System.out.println("[NetreadThread] It's started\n");
		while (mRunning) {
			try {
				mReceivePacket = new DatagramPacket(mReceiveData, mReceiveData.length);
				mSocket.receive(mReceivePacket);
				if(NetworkUtils.insertByteArrayToInt(mReceivePacket.getData(), 3)!=KayaoValues.MAGIC_NUMBER && mReceivePacket.getData()[0] == KayaoValues.PLAYING_REQUEST_MESSAGE){
					MessageHandler.statistics(mReceiveData[0], "netread2");					
				} else {
					MessageHandler.statistics(mReceiveData[4], "netread");
				}
				//treat it
				byte[] recData = new byte[MAX_PACKET_SIZE];
				System.arraycopy(mReceiveData, 0, recData, 0, mReceiveData.length);
				MessageHandler.insertIncomingMessage(mReceivePacket.getAddress().toString().substring(1), recData);
				for(int i = 0; i < mReceiveData.length; i++) {
					mReceiveData[i] = 9;
				}
			} catch (IOException e) {
				System.out.println("NetreadThread - error in run: "	+ e.getMessage());
				mDead = true;
			}
		}
	}
}
